﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication
{
    public partial class ShutDownTest : Form
    {
        private bool isThreadQuite = false;
        public ShutDownTest()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            isThreadQuite = false;
            Thread t = new Thread(new ThreadStart(ThreadHandler));
            t.IsBackground = true;
            t.Start();
            button1.Enabled = false;
        }

        private void ThreadHandler()
        {
            try
            {
                int min = Convert.ToInt32(maskedTime.Text);
                int second = 60 * min;
                while ((second--) > 0)
                {
                    if (isThreadQuite)
                        break;

                    updateControllerValue(second);
                    Thread.Sleep(1000);
                }

                if (isThreadQuite == false)
                    shutdown(0);
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                updateButton();
            }
        }

        private void updateControllerValue(int second)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((MethodInvoker)(() => lblRemainTime.Text = second.ToString()));
            }
            else
            {
                lblRemainTime.Text = second.ToString();
            }
        }

        private void updateButton()
        {
            if (this.InvokeRequired)
            {
                this.Invoke((MethodInvoker)(() => button1.Enabled = true));
            }
            else
            {
                button1.Enabled = true;
            }
        }

        private void shutdown(int second)
        {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.FileName = "cmd.exe";
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardInput = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.CreateNoWindow = true;
            proc.Start();
            proc.StandardInput.WriteLine("shutdown -s -t "+second);
            proc.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            isThreadQuite = true;
        }
    }
}
